package com.zongxingh.falcon.mq.producer;

import com.zongxingh.falcon.mq.config.MqProperties;
import com.zongxingh.falcon.mq.constant.MqType;
import com.zongxingh.falcon.mq.producer.impl.RabbitMqProducer;
import com.zongxingh.falcon.mq.producer.impl.RocketMqProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Introduction:  <简介>
 * Package Name:  com.zongxingh.falcon.mq.producer
 * Project Name:  mq
 * Author:  zongxingh
 * Email： zongxingh@163.com
 * Tel: 157*****778
 * Create Time:  2020/9/22 15:03
 */
public class MQProducerFactory {
    private static final Logger LOGGER = LoggerFactory.getLogger(MQProducerFactory.class);

    private static Map<String, MqProducer> producerMap = new HashMap<>();

    public static MqProducer createProducer(String producerGroup, MqProperties properties) {
        if (null == properties.getMqType() || "".equals(properties.getMqType())){
            LOGGER.error("获得消息生产者，当前没有配置消息队列类型。");
            return null;
        }
        else if (MqType.ROCKET_MQ.getCode().equals(properties.getMqType())) {
            return getRocketMqProducer(producerGroup, properties);
        }
        else if (MqType.RABBIT_MQ.getCode().equals(properties.getMqType())) {
            return getRabbitMqProducer(producerGroup, properties);
        }
        else {
            LOGGER.error("获得消息生产者，当前不支持该消息队列，消息队列类型为：{}", properties.getMqType());
            return null;
        }

    }

    /**
     * 根据producerName 从容器中获得 Producer
     *
     * @param producerName
     * @return
     */
    private static MqProducer getProducer(String producerName) {
        if (producerMap.size() == 0) {
            return null;
        }
        LOGGER.debug("创建消息生产者，producerName为[{}]的生产者已经存在，不在重新创建。", producerName);
        return producerMap.get(producerName);
    }

    /**
     * 获得RocketMq Producer
     * @param producerGroup
     * @param properties
     * @return
     */
    private static MqProducer getRocketMqProducer(String producerGroup, MqProperties properties) {
        MqProducer mqProducer = getProducer(producerGroup);
        if (null == mqProducer) {
            RocketMqProducer rocketMqProducer = new RocketMqProducer(producerGroup, properties);
            producerMap.put(producerGroup, rocketMqProducer);
            return rocketMqProducer;
        }
        return mqProducer;
    }

    /**
     * 获得RabbitMq Producer
     * @param producerGroup
     * @param properties
     * @return
     */
    private static MqProducer getRabbitMqProducer(String producerGroup, MqProperties properties) {
        MqProducer mqProducer = getProducer(producerGroup);
        if (null == mqProducer) {
            RabbitMqProducer rabbitMqProducer = new RabbitMqProducer();
            producerMap.put(producerGroup, rabbitMqProducer);
            return rabbitMqProducer;
        }
        return mqProducer;
    }

}
